package com.demo.paypalmanagement.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.demo.paypalmanagement.common.EmailUtils;
import com.demo.paypalmanagement.common.RedisConstants;
import com.demo.paypalmanagement.model.entity.Users;
import com.demo.paypalmanagement.model.vo.Result;
import com.demo.paypalmanagement.service.CaptchaService;
import com.demo.paypalmanagement.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/com/captcha")
public class CaptchaController {
    private final CaptchaService captchaService;
    private final EmailUtils emailUtils;
    @Autowired
    private IUsersService usersService;
    public CaptchaController(CaptchaService captchaService, EmailUtils emailUtils) {
        this.captchaService = captchaService;
        this.emailUtils = emailUtils;
    }

    // 生成验证码并发送邮件
    @PostMapping("/generate")
    public Result generateCaptcha(@RequestParam String email) throws MessagingException {

        boolean existsByEmail = usersService.existsByEmail(email);
        if(existsByEmail){
            return Result.fail(400, "email已被绑定");
        }

        // 生成4位随机验证码
        String captcha = RandomUtil.randomNumbers(4);
        // 保存验证码到 Redis
        captchaService.saveCaptcha(RedisConstants.REGISTER_CAPTCHA_KEY_PREFIX,email, captcha);
        // 发送验证码邮件
        emailUtils.sendMessage(email,"注册验证码","有效期1分钟："+ captcha);
        return Result.success("已经发送验证码");
    }
    // 找回密码
    @PostMapping("/retrieve")
    public Result retrieveCaptcha(@RequestParam String email,@RequestParam String account) throws MessagingException {
        Users user = usersService.getUserByEmailAndAccount(email,account);
        if(ObjectUtil.isEmpty(user)){
            return Result.fail(400, "信息不存在，请检查你的用户或者邮箱");
        }
        // 生成4位随机验证码
        String captcha = RandomUtil.randomNumbers(4);
        // 保存验证码到 Redis
        captchaService.saveCaptcha(RedisConstants.FIND_PWD_CAPTCHA_KEY_PREFIX,email, captcha);
        // 发送验证码邮件
        emailUtils.sendMessage(email,"找回密码验证码","有效期1分钟："+ captcha);
        return Result.success("已经发送验证码");
    }


}
